<template>
  <div class="order-detail-page">
    <div class="container-custom py-8">
      <AppBreadcrumb :items="breadcrumbs" />
      
      <div v-if="pending" class="mt-8 animate-pulse">
        <div class="card p-6">
          <div class="h-40 bg-gray-200 rounded" />
        </div>
      </div>
      
      <div v-else-if="order" class="mt-8 space-y-6">
        <!-- 订单状态 -->
        <div class="card p-6">
          <div class="flex items-center justify-between mb-6">
            <div>
              <h1 class="text-2xl font-bold mb-2">订单详情</h1>
              <div class="flex items-center space-x-4">
                <span class="text-sm text-gray-600">订单号：{{ order.orderNo }}</span>
                <OrderStatus :status="order.status" />
              </div>
            </div>
            <div class="text-right">
              <div class="text-sm text-gray-600 mb-1">订单金额</div>
              <div class="text-3xl font-bold text-primary-600">
                ¥{{ order.totalAmount.toFixed(2) }}
              </div>
            </div>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-3 gap-6 pt-6 border-t">
            <div>
              <div class="text-sm text-gray-600 mb-1">创建时间</div>
              <div class="font-medium">{{ formatDate(order.createdAt) }}</div>
            </div>
            <div v-if="order.paidAt">
              <div class="text-sm text-gray-600 mb-1">支付时间</div>
              <div class="font-medium">{{ formatDate(order.paidAt) }}</div>
            </div>
            <div>
              <div class="text-sm text-gray-600 mb-1">支付方式</div>
              <div class="font-medium">{{ paymentMethodMap[order.paymentMethod] }}</div>
            </div>
          </div>
        </div>
        
        <!-- 商品列表 -->
        <div class="card p-6">
          <h2 class="text-xl font-bold mb-4">商品清单</h2>
          <div class="space-y-4">
            <div
              v-for="item in order.items"
              :key="item.id"
              class="flex items-center space-x-4 pb-4 border-b last:border-b-0 last:pb-0"
            >
              <NuxtLink :to="`/products/${item.productId}`" class="flex-shrink-0">
                <NuxtImg
                  :src="item.productCover"
                  :alt="item.productTitle"
                  class="w-24 h-24 object-cover rounded"
                />
              </NuxtLink>
              
              <div class="flex-1 min-w-0">
                <NuxtLink
                  :to="`/products/${item.productId}`"
                  class="text-lg font-medium hover:text-primary-600 line-clamp-1"
                >
                  {{ item.productTitle }}
                </NuxtLink>
                <div class="text-sm text-gray-500 mt-2">
                  数量：{{ item.quantity }}
                </div>
              </div>
              
              <div class="text-right">
                <div class="text-lg font-bold">¥{{ item.price.toFixed(2) }}</div>
                <div class="text-sm text-gray-500">
                  小计：¥{{ (item.price * item.quantity).toFixed(2) }}
                </div>
              </div>
            </div>
          </div>
          
          <div class="mt-6 pt-6 border-t flex justify-end">
            <div class="text-right">
              <div class="text-gray-600">订单总额：</div>
              <div class="text-2xl font-bold text-primary-600 mt-1">
                ¥{{ order.totalAmount.toFixed(2) }}
              </div>
            </div>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div v-if="order.status === 'pending'" class="flex justify-end space-x-4">
          <button
            class="btn-outline px-6 py-3"
            @click="handleCancel"
          >
            取消订单
          </button>
          <button
            class="btn-primary px-6 py-3"
            @click="handlePay"
          >
            立即支付
          </button>
        </div>
      </div>
      
      <div v-else class="mt-8 text-center py-16">
        <div class="i-mdi-alert-circle-outline text-8xl text-gray-300 mb-4" />
        <p class="text-gray-600">订单不存在</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Order } from '~/types'
import dayjs from 'dayjs'

definePageMeta({
  middleware: 'auth',
})

const route = useRoute()
const router = useRouter()
const orderId = route.params.id as string

const breadcrumbs = [
  { label: '我的订单', path: '/user/orders' },
  { label: '订单详情' },
]

const paymentMethodMap = {
  alipay: '支付宝',
  wechat: '微信支付',
}

// 获取订单详情
const { data: response, pending } = await useFetch<{ code: number; message: string; data: Order }>(`/api/orders/${orderId}`)

const order = computed(() => response.value?.data || null)

function formatDate(date: string) {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

async function handleCancel() {
  if (!confirm('确定要取消订单吗？')) {
    return
  }
  
  try {
    await $fetch(`/api/orders/${orderId}/cancel`, {
      method: 'POST',
    })
    
    router.push('/user/orders')
  } catch (error: any) {
    alert(error.message || '取消订单失败')
  }
}

function handlePay() {
  router.push(`/payment/${orderId}`)
}

// SEO
useSeoMeta({
  title: '订单详情 - 代码小库',
  robots: 'noindex',
})
</script>

<style scoped>
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>

